<!-- 添加谜题页面 -->
<template>
	<view class="body">
		<text class="text1" v-if="ItemId == -1">新增谜题</text>
		<text class="text1" v-else>修改谜题</text>

		<view class="form-submit">

			<!--题目类型-->
			<view class="choose-type">
				<text class="fontWeight">题目类型：</text>
				<radio-group name="choose-type">
					<radio value="2" :checked="puzzleType == 2" @click="changeType(2)">单选</radio>
					<radio value="1" :checked="puzzleType == 1" @click="changeType(1)">多选</radio>
					<radio value="3" :checked="puzzleType == 3" @click="changeType(3)">判断</radio>
					<radio value="0" :checked="puzzleType == 0" @click="changeType(0)">填空</radio>
				</radio-group>
			</view>

			<view style="display: flex;">
				<text class="fontWeight WIDTH_120">题目：</text>
				<input style="flex: 1;" placeholder="请输入题目..." v-model="puzzleName" maxlength="20" />
			</view>

			<view class="text-area-ct">
				<text class="fontWeight">内容：</text>
				<textarea placeholder="请输入谜题内容..." v-model="puzzleContentDTO.contentText"
					name="inputContentText"></textarea>
			</view>

			<view>
				<view style="margin-bottom: 0.3rem;">
					<!--如果是  1,2选择，则显示这个start-->
					<view class="optionAdd" v-if="[1, 2].includes(puzzleType)">
						<text class="fontWeight">选项：</text>
						<button @click="addAnswer">+ 添加</button>
					</view>

					<!--答案区域A:  B: ...-->
					<view class="chooseAnswerCt" v-if="puzzleType == 1 || puzzleType == 2">
						<view v-for="(item, index) in optionList" :key="index">
							<text>{{ String.fromCharCode('A'.charCodeAt(0) + index) }}.</text>
							<input placeholder="输入答案..." @input="updateSelectContent(item,$event.target.value)"
								v-model="item.selectContent" name='selectContent' />
							<uni-icons type="trash-filled" size="1.5rem" @click="delAnswer(index)"></uni-icons>
						</view>
					</view>

					<!--如果是  1,2选择，则显示这个end-->
				</view>

				<!--正确答案的设置start-->
				<view class="text-area-ct">
					<text class="trueAnswer">正确答案：</text>

					<!--如果是 0填空，则显示这个start-->
					<textarea v-show="puzzleType == 0" @input="inputTheAnswer()" placeholder="请输入答案..."
						v-model="puzzleAnswerTianKong"></textarea>
					<!--如果是 0填空，则显示这个end-->

					<!--如果是  1,2选择，则显示这个start-->
					<!--多选-->
					<checkbox-group class="selectGroup" v-if="puzzleType == 1" @change="updatePuzzleAnswer">
						<checkbox v-for="(item,index) in optionList" :key="index"
							:checked="puzzleAnswerAsArray.includes(String.fromCharCode('A'.charCodeAt(0) + index))"
							:value="String.fromCharCode('A'.charCodeAt(0) + index)">
							{{ String.fromCharCode('A'.charCodeAt(0) + index) }}
						</checkbox>
					</checkbox-group>

					<!--单选-->
					<radio-group class="selectGroup" v-if="puzzleType == 2" @change="updatePuzzleAnswerSingle">
						<radio v-for="(item, index) in optionList" :key="index"
							:checked="String.fromCharCode('A'.charCodeAt(0) + index) == puzzleAnswerDanXuan"
							:value="String.fromCharCode('A'.charCodeAt(0) + index)">
							{{ String.fromCharCode('A'.charCodeAt(0) + index) }}
						</radio>
					</radio-group>
					<!--如果是  1，2选择，则显示这个end-->

					<!--如果是判断，则显示这个start-->
					<radio-group class="selectGroup" v-if="puzzleType == 3" @change="updatePuzzleAnswerJudge">
						<radio value="true" :checked="puzzleAnswerJudge == 'true'">✓</radio>
						<radio value="false" :checked="puzzleAnswerJudge == 'false'">×</radio>
					</radio-group>
					<!--如果是判断，则显示这个end-->

					<!--星星展示start-->
					<view class="star-show-ct">
						<text class="fontWeight">难度星级：</text>
						<view v-for="index in 5" :key="index" :label="index">
							<uni-icons :type="iconType(index)" :size="25" color="red"
								@click="changeIcon(index)"></uni-icons>
						</view>
					</view>
					<!--星星展示end-->
				</view>
			</view>

			<!--解题思路start-->
			<view>
				<view class="text-area-ct">
					<text class="fontWeight">解题思路：</text>
					<textarea placeholder="选填" v-model="clue"></textarea>
				</view>
			</view>
			<!--解题思路end-->

			<view style="opacity: 0; padding: 64px 0 0;"></view>
		</view>

		<button class="submit-btn" @click="formSubmit">提交</button>

	</view>
</template>

<script>
	import {
		addPuzzle,
		getPuzzleMoreMsg, //根据谜题id展示详细谜题信息
		updatePuzzle,
	} from '@/config/api.js'

	export default {
		onLoad(option) {
			console.log("editing puzzle as user id:", this.$store.state.userInfo.id)
			const id = this.$store.state.userInfo.id
			this.userId = id;

			// 拿去option的值
			console.log("editing puzzle id", option.itemId)
			this.ItemId = option.itemId ? option.itemId : -1

			if (option.itemId === -1) {
				//出题模式
				this.changeType(0);

			} else {
				//修改谜题模式
				this.fetchItemMsg()
				//抓取谜题全部信息
			}

		},
		data() {
			return {

				ItemId: -1, //id为-1，则为出题模式，为具体 的id，为修改谜题模式

				selectIcon: 0, //默认不选中的星级,0表示1星

				//传送的 body
				puzzleDTO: {

				},

				labelList: [{
					labelName: ""
				}], //标签列表   类型是数组                 true

				optionList: [{
					selectContent: '', //选项内容          true
					tbSelect: 'A', //选项(ABCDE..)          true  2-6
				}], //谜题选项内容,谜题回答类型为选择才要    false
				puzzleAnswer: '', //谜题答案 eg：AB         true
				puzzleContentDTO: {
					contentText: "", //谜题内容文本    true
					media: "", //谜题内容媒体文件url   false



				}, //谜题内容（图片，文本）               true
				puzzleKinds: 0, //谜题分类/类型
				puzzleName: "", //谜题名称
				puzzleType: 0, //0填空,1多选选择 2单选 3判断  true
				star: 0, //1-5                           true
				userId: -1, //  true
				clue: '', // 谜题线索 					   false
				star: 1,


				puzzleAnswerTianKong: '',
				puzzleAnswerAsArray: '', //多选答案
				puzzleAnswerDanXuan: '', //单选答案
				puzzleAnswerJudge: '', //判断答案
				//PuzzleOptionsDTO
				//
				//puzzleAnswerAsString: null, //单选答案
				//puzzleAnswerDuoXuan: '', //多选答案

				// 新增单个谜题
				addPuzzleItem: {},

			}
		},
		methods: {
			// 根据谜题id展示详细谜题信息
			async fetchItemMsg() {
				const res = await getPuzzleMoreMsg(this.ItemId)
				console.log("根据谜题id展示详细谜题信息==>", res)
				var puzzleUpdateMsg = JSON.parse(JSON.stringify(res))

				this.puzzleType = puzzleUpdateMsg.puzzleType
				this.puzzleName = puzzleUpdateMsg.puzzleName
				this.puzzleContentDTO.contentText = puzzleUpdateMsg.puzzleContentDTO.contentText //内容
				this.optionList = puzzleUpdateMsg.optionList ? puzzleUpdateMsg.optionList : [] //谜题选项
				this.selectIcon = puzzleUpdateMsg.star - 1 //难度
				this.clue = puzzleUpdateMsg.clue

				this.puzzleAnswerTianKong = puzzleUpdateMsg.puzzleAnswer
				this.puzzleAnswerAsArray = puzzleUpdateMsg.puzzleAnswer
				this.puzzleAnswerDanXuan = puzzleUpdateMsg.puzzleAnswer
				this.puzzleAnswerJudge = puzzleUpdateMsg.puzzleAnswer

			},

			// 填空输入答案函数
			inputTheAnswer() {
				console.log("输入的值为：", this.puzzleAnswerTianKong)
			},

			// 多选
			updatePuzzleAnswer(checkedValues) {
				this.puzzleAnswerAsArray = JSON.stringify(checkedValues.detail.value.sort())
				console.log("puzzleAnswerAsArray:", this.puzzleAnswerAsArray)
			},

			// 单选
			updatePuzzleAnswerSingle(selectValue) {
				this.puzzleAnswerDanXuan = selectValue.detail.value
				console.log("puzzleAnswerDanXuan:", this.puzzleAnswerDanXuan)
			},

			// 判断
			updatePuzzleAnswerJudge(selectValue) {
				this.puzzleAnswerJudge = selectValue.detail.value
				console.log("puzzleAnswerJudge:", this.puzzleAnswerJudge)
			},

			// 选项
			updateSelectContent(item, value) {
				console.log("item===>" + item, "value===>" + value)
				//item.selectContent = value;
			},

			//星级的选择函数
			iconType(index) {
				// 根据选中状态返回不同的图标类型
				return index <= this.selectIcon ? 'star-filled' : 'star';
			},
			changeIcon(index) {
				// 修改选中状态，触发重新渲染图标
				this.selectIcon = index
			},

			//表单的提交或撤销
			async formSubmit() {
				//console.log('form发生了submit事件，携带数据为：' + JSON.stringify(e.detail.value))

				console.log("选择的答题模式是：-->", this.puzzleType);

				if (this.puzzleType == 0) {
					optionList: [], //初始化为空
					this.puzzleAnswer = '' //初始化为空
					//填空

					this.puzzleAnswer = this.puzzleAnswerTianKong
					console.log("填空答案是：-->", this.puzzleAnswer)
				}

				if (this.puzzleType == 1) {
					// 初始化
					optionList: [{
						selectContent: '', //选项内容          true
						tbSelect: 'A', //选项(ABCDE..)          true  2-6
					}], //谜题选项内容,谜题回答类型为选择才要    false
					//多选
					this.puzzleAnswer = ''

					console.log("多选答案是：-->", this.puzzleAnswerAsArray, typeof(this.puzzleAnswerAsArray))
					//得到一个数组-----》答案是：-->["A","B"]
					//let puzzleAnswer = ''
					// for(let i =0;i<this.puzzleAnswerAsArray.length;i++){
					// 	puzzleAnswer = puzzleAnswer + this.puzzleAnswerAsArray[i]

					// }

					// let puzzleAnswer = ''
					// const match = this.puzzleAnswerAsArray.match(/"(.*?)"/g);

					// const content = match ? match.map(s=>s.slice(1,-1)):[]

					// for (let i = 0; i < this.puzzleAnswerAsArray.length; i++) {
					// 	puzzleAnswer = puzzleAnswer + this.puzzleAnswerAsArray[i]
					// }
					this.puzzleAnswer = this.puzzleAnswerAsArray
					//为什么得到的puzzleAnswer是数组啊？？？？
				}

				if (this.puzzleType == 2) {
					this.puzzleAnswer = this.puzzleAnswerDanXuan
				}

				if (this.puzzleType == 3) {
					this.puzzleAnswer = this.puzzleAnswerJudge
				}


				var formdata = {} //传递的最终数据

				formdata.optionList = this.optionList; //选项
				for (var i = 0; i < formdata.optionList.length; i++) {
					formdata.optionList[i].tbSelect = String.fromCharCode('A'.charCodeAt(0) + i)
				}

				formdata.puzzleName = this.puzzleName; //名字
				formdata.puzzleAnswer = this.puzzleAnswer; //答案
				formdata.clue = this.clue; //选项

				formdata.userId = this.userId; //用户id
				formdata.star = this.selectIcon + 1;


				/////////????????????????????????????????????????????????????
				formdata.labelList = this.labelList; //标签的list


				var PuzzleLabelDTO = []

				formdata.labelList = PuzzleLabelDTO

				// var PuzzleOptionsDTO = []
				// PuzzleOptionsDTO.optionList =  this.optionList
				// PuzzleOptionsDTO.puzzleAnswer = this.puzzleAnswer


				//formdata.PuzzleOptionsDTO = PuzzleOptionsDTO


				var puzzleContentDTO = {}
				puzzleContentDTO.contentText = this.puzzleContentDTO.contentText

				formdata.puzzleKinds = this.puzzleKinds
				formdata.puzzleName = this.puzzleName
				formdata.puzzleType = this.puzzleType

				formdata.puzzleContentDTO = puzzleContentDTO;

				//formdata.puzzleType = this.puzzleType

				let resultMsg = '出错了!'
				try {
					if (this.ItemId == -1) {
						await addPuzzle(formdata);
						resultMsg = '添加谜题成功'
					} else {
						formdata.id = this.ItemId
						formdata.puzzleContent = this.puzzleContentDTO
						await updatePuzzle(formdata)
						resultMsg = '修改谜题成功'
					}

					uni.showModal({
						content: resultMsg,
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack({
									delta: 1
								})
							}
						}
					})
				} catch (e) {
					console.error(e)

					uni.showModal({
						content: resultMsg,
						showCancel: false,
					})
				}
			},

			changeType(value) {
				this.puzzleType = value;
				this.puzzleAnswer = ''
			},

			updateSelectedOption(value) {
				this.selectedOption = value.slice(0, 1);
			},

			update_puzzle_type(type) {
				this.puzzleType = type;
				console.log("this.puzzleType=" + this.puzzleType);
				this.puzzleAnswer = ''
			},

			addAnswer() {
				let newAns = {};
				if (this.optionList.length < 6 && (this.puzzleType == 1 || this.puzzleType == 2)) {
					this.optionList.push({
						selectContent: '',
					})
				} else {
					uni.showToast({
						title: "不超过6个选项",
						icon: 'error'
					})
				}
			},

			delAnswer(index) {
				if (this.optionList.length > 1) {
					this.optionList.splice(index, 1);
					this.puzzleAnswerAsArray = ''
				}
			},
		},
	}
</script>

<style scoped lang="scss">
	.body {
		--gray-color: rgb(248, 248, 248);
		--gold-color: gold;
		--blue-color: #1772F6;

		display: flex;
		flex-flow: column;
		height: 100%;
		width: 100%;
		background: linear-gradient(to bottom, var(--blue-color) 5%, var(--gray-color) 30%);
	}

	.text1 {
		text-align: center;
		margin: 0.9rem 0;
		color: white;
		font-weight: bold;
		font-size: 1.5rem;
		letter-spacing: 0.5rem;
	}

	.form-submit {
		display: flex;
		flex-flow: column;
		gap: 0.5rem;
		overflow-y: auto;
		background-color: var(--gray-color);
		box-sizing: border-box;
		margin: 0 0.5rem;
		padding: 0.3rem;
		border-radius: 0.7rem 0.7rem 0 0;
		color: #13242d;
	}

	.fontWeight {
		font-weight: bold;
	}

	.form-submit>view {
		background-color: white;
		padding: 0.4rem 0.3rem;
		border-radius: 0.5rem;
	}

	.choose-type {
		display: flex;
		flex-wrap: wrap;

		text {
			white-space: nowrap;

		}

		radio-group {
			display: flex;
			flex: 1;

			radio {
				flex: 1;
				white-space: nowrap;
			}
		}
	}

	.text-area-ct {
		display: flex;
		flex-direction: column;
		align-items: left;
		gap: 0.3rem;
	}

	.text-area-ct>textarea {
		width: 100%;
		height: 6rem;
	}

	.trueAnswer {
		color: #CB2D01;
		font-weight: bold;
	}

	.star-show-ct {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.optionAdd {
		display: flex;
		align-items: center;
		width: fit-content;
	}

	.optionAdd>button {
		background-color: var(--blue-color);
		color: white;
		padding: 0.2rem 0.4rem;
		line-height: initial;
		font-size: 0.9rem;
	}

	.chooseAnswerCt {
		padding: 0.2rem 0;
	}

	.chooseAnswerCt>view {
		display: flex;
		flex-direction: row;
		align-items: center;
		gap: 0.5rem;
		padding: 0.5rem;
	}

	.chooseAnswerCt>view:nth-child(odd) {
		background-color: var(--gray-color);
	}

	.chooseAnswerCt>view>input {
		flex: 1;
	}

	.selectGroup {
		display: flex;
		align-items: center;
		gap: 0.7rem;
	}

	.submit-btn {
		position: fixed;
		z-index: 100;
		bottom: 1rem;
		left: 50%;
		transform: translateX(-50%);
		background-color: var(--blue-color);
		color: white;
		width: 60%;
	}
</style>